/* eslint-disable no-shadow */
/**
 * 猎聘
 */
import React from 'react';
import { Form, Input, Select, Button, message, Card, Icon, Alert, Spin, InputNumber } from 'antd';
import { BottomAction } from '@/components';
import { useRequest } from '@/hooks';
import useChannelDict from './useChannelDict';
import DropDownCascader from '../../Setting/containers/DropDownCascader';
import { getCategoryTree } from '../../Setting/service';
import useRecruitOutwardsChannelDetail from './useRecruitOutwardsChannelDetail';
import useRecruitOutwardsChannelUpdate from './useRecruitOutwardsChannelUpdate';

const { Option } = Select;
const channelCode = 'liepin';
const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
    }
};
const filterTree = tree =>
    tree.map(({ children, positionCategoryCode, positionCategoryName, ...props }) => ({
        children: children && children.length > 0 ? filterTree(children) : '',
        label: positionCategoryName,
        value: positionCategoryCode,
        ...props
    }));
const flat = tree =>
    tree.reduce((pre, curr) => {
        const { children, label, value } = curr;
        let next = [{ label, value }];
        if (children && children.length) {
            next = [...next, ...flat(children)];
        }
        return [...pre, ...next];
    }, []);
const arrToStr = arr => (arr && arr.length ? arr.join(',') : '');
const strToArr = str => (str ? str.split(',') : []);
const salaryFormatter = unit => value => `${value}${unit}`;
const salaryParser = unit => value => value.replace(unit, '');
const SalaryUnitWrapper = ({ children }) => <span style={{ margin: '0 8px', fontWeight: 'bolder' }}>{children}</span>;
function LiepinForm({ form, outwardId, onSuccess, onError }) {
    const { getFieldDecorator, getFieldsValue, getFieldValue, validateFields } = form;
    const {
        workExperience,
        educationDegree,
        feedbackPeriod,
        positionPoint,
        loading: dictLoading
    } = useChannelDict(channelCode, ['workExperience', 'educationDegree', 'feedbackPeriod', 'positionPoint']);
    const [runSubmit, submitLoading] = useRecruitOutwardsChannelUpdate(onSuccess, onError);
    const [data, loading] = useRecruitOutwardsChannelDetail(outwardId, channelCode);
    // 职位类别树
    const { data: categoryTree, loading: categoryLoading } = useRequest(() => getCategoryTree(channelCode), {
        refreshDeps: [],
        formatResult: res => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    return filterTree(resData || []);
                }
                message.error(msg);
            }
            return null;
        }
    });
    React.useEffect(() => {
        const channelRecruitInfo = JSON.parse(data?.channelRecruitInfo || null);
        if (!channelRecruitInfo) {
            return;
        }
        const { detailTags, ejobJobtitle } = channelRecruitInfo;
        const extend = {
            detailTags: strToArr(detailTags),
            ejobJobtitle: strToArr(ejobJobtitle)
        };
        const values = { ...channelRecruitInfo, ...extend };
        const formValues = getFieldsValue();
        const exists = key => Object.keys(formValues).indexOf(key) !== -1;
        form.setFieldsValue(
            Object.keys(values).reduce((pre, curr) => {
                if (exists(curr)) {
                    return { ...pre, [curr]: values[curr] };
                }
                return { ...pre };
            }, {})
        );
    }, [data]);
    const handleSubmit = e => {
        e.preventDefault();

        form.validateFieldsAndScroll(async (err, values) => {
            if (err) {
                return;
            }
            const sourceData = JSON.parse(data?.channelRecruitInfo || null) || {}; // shit,将后端返回的未展示在界面上的数据原封不动传至后台
            const { detailWorkyearArea, detailTags, ejobJobtitle } = values;
            const [detailWorkyearlow, detailWorkyearhigh] = (detailWorkyearArea || '').split(',');
            const flatArr = flat(categoryTree);
            const extend = {
                detailWorkyearlow,
                detailWorkyearhigh,
                detailTags: arrToStr(detailTags),
                ejobJobtitle: arrToStr(ejobJobtitle),
                positionCategoryNames: arrToStr(
                    ejobJobtitle.map(id => flatArr.find(item => item.value === id)?.label).filter(_ => _)
                )
            };
            runSubmit(outwardId, channelCode, JSON.stringify({ ...sourceData, ...values, ...extend }));
        });
    };
    // 标准的
    const renderOptions = dict => {
        if (!dict || !dict.length) {
            return null;
        }
        return dict.map(item => (
            <Option value={item.selectValue} key={item.selectValue}>
                {item.selectName}
            </Option>
        ));
    };
    const checkPrice = (rule, value, callback) => {
        const from = getFieldValue('ejobMonthlysalaryLow');
        const to = getFieldValue('ejobMonthlysalaryHigh');
        const unit = getFieldValue('ejobSalaryMonth');
        if (!from || !to || !unit) {
            return callback('请输入职位参考薪资');
        }
        if (from - to > 0) {
            return callback('薪资最小值不能大于最大值');
        }
        if (from * 2 < to) {
            return callback('薪资最大值不能大于最小值的两倍');
        }
        return callback();
    };
    const handleForceValidate = keys => {
        validateFields(keys, { force: true });
    };
    React.useEffect(() => {
        handleForceValidate(['temp']);
    }, [getFieldValue('ejobMonthlysalaryLow'), getFieldValue('ejobMonthlysalaryHigh')]);
    const renderSalaryForm = () =>
        getFieldDecorator('temp', {
            initialValue: 1,
            rules: [{ required: true, message: '\r' }, { validator: checkPrice }]
        })(
            <div style={{ display: 'flex' }}>
                <Form.Item label="" colon={false} style={{ width: '24%', marginBottom: 0 }}>
                    {getFieldDecorator('ejobMonthlysalaryLow')(
                        <InputNumber
                            precision={0}
                            min={1}
                            style={{ width: '100%' }}
                            placeholder="请输入"
                            formatter={salaryFormatter('K')}
                            parser={salaryParser('K')}
                        />
                    )}
                </Form.Item>
                <SalaryUnitWrapper>-</SalaryUnitWrapper>
                <Form.Item label="" colon={false} style={{ width: '24%', marginBottom: 0 }}>
                    {getFieldDecorator('ejobMonthlysalaryHigh')(
                        <InputNumber
                            min={1}
                            precision={0}
                            style={{ width: '100%' }}
                            placeholder="请输入"
                            formatter={salaryFormatter('K')}
                            parser={salaryParser('K')}
                        />
                    )}
                </Form.Item>
                <SalaryUnitWrapper>*</SalaryUnitWrapper>
                <Form.Item label="" colon={false} style={{ width: '24%', marginBottom: 0 }}>
                    {getFieldDecorator('ejobSalaryMonth')(
                        <InputNumber
                            min={1}
                            precision={0}
                            style={{ width: '100%' }}
                            placeholder="请输入"
                            // formatter={salaryFormatter('月')}
                            parser={salaryParser('月')}
                        />
                    )}
                </Form.Item>
                {/* <div style={{ marginLeft: 8 }}>{data?.companyCurrencyCode || '薪'}</div> */}
                <div style={{ marginLeft: 8 }}>薪</div>
            </div>
        );

    const renderWarnIcon = style => <Icon style={style || {}} type="warning" theme="twoTone" twoToneColor="#faad14" />;
    const renderWarnLabel = text => (
        <div style={{ position: 'relative', display: 'inline-block', overflowX: 'visible' }}>
            {renderWarnIcon({
                position: 'absolute',
                top: 14,
                left: -30,
                fontSize: '12px'
            })}

            {text}
        </div>
    );
    return (
        <Card
            bordered={false}
            title={<div style={{ margin: '10px 0' }}>渠道发布信息</div>}
            loading={loading || dictLoading}
            extra={data?.channelLogoUrl && <img height="44" src={data?.channelLogoUrl || ''} alt="BOSS直聘" />}
        >
            <BottomAction>
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    提交
                </Button>
            </BottomAction>
            <Alert
                style={{ marginBottom: 24 }}
                message={
                    <div>
                        注：加&nbsp;
                        {renderWarnIcon()}
                        &nbsp;内容在确认发布后，将无法修改
                    </div>
                }
                type="warning"
            />
            <Form {...formItemLayout} className="ant-advanced-search-form">
                <Form.Item label={renderWarnLabel('职位名称')}>
                    {getFieldDecorator('ejobTitle', {
                        rules: [
                            { required: true, message: '请输入职位名称' },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 60) {
                                        callback('职位名称最大长度不能超过60个字符');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input disabled={data?.hasRelease} placeholder="请输入职位名称" />)}
                </Form.Item>
                <Form.Item label="职位类别">
                    <Spin spinning={categoryLoading}>
                        {getFieldDecorator('ejobJobtitle', {
                            rules: [{ required: true, message: '请选择职位类别' }]
                        })(
                            <DropDownCascader
                                options={categoryTree || []}
                                placeholder="选择职位类别"
                                maxCount={3}
                                changeOnLastLevel
                                onChange={() => {}}
                            />
                        )}
                    </Spin>
                </Form.Item>
                <Form.Item label="职位亮点">
                    {getFieldDecorator('detailTags', {
                        initialValue: undefined,
                        rules: [
                            {
                                required: true,
                                message: '请选择职位亮点'
                            },
                            {
                                validator(rule, value, callback) {
                                    if (value?.length > 10) {
                                        callback('职位亮点不能超过10个');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <Select
                            showArrow
                            mode="tags"
                            showSearch
                            allowClear
                            placeholder="选择职位亮点"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                        >
                            {positionPoint?.map(item => (
                                <Option
                                    value={item.selectValue}
                                    key={item.selectName}
                                    disabled={
                                        form.getFieldValue('detailTags')?.length >= 10 &&
                                        !form.getFieldValue('detailTags')?.includes(item.selectName)
                                    }
                                >
                                    {item.selectName}
                                </Option>
                            ))}
                        </Select>
                    )}
                </Form.Item>
                <Form.Item label="工作地址">{getFieldDecorator('channelWorkCityName')(<Input disabled />)}</Form.Item>
                <Form.Item label="职位薪资">{renderSalaryForm()}</Form.Item>
                <Form.Item label="工作经历">
                    {getFieldDecorator('detailWorkyearArea', {
                        rules: [{ required: true, message: '请选择工作经历' }]
                    })(<Select placeholder="选择工作经历">{renderOptions(workExperience)}</Select>)}
                </Form.Item>
                <Form.Item label="学历要求">
                    {getFieldDecorator('detailEdulevel', {
                        rules: [{ required: true, message: '请选择学历要求' }]
                    })(<Select placeholder="选择学历要求">{renderOptions(educationDegree)}</Select>)}
                </Form.Item>
                <Form.Item label="职位描述">
                    {getFieldDecorator('detailDutyQualify', {
                        rules: [
                            { required: true, message: '请输入职位描述' },
                            {
                                validator: (rule, value, callback) => {
                                    if (value?.length > 2000) {
                                        callback('职位描述最大长度不能超过2000个字符');
                                        return;
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input.TextArea rows={24} maxLength={2000} placeholder="请输入职位描述" />)}
                </Form.Item>
                <Form.Item label="反馈时长">
                    {getFieldDecorator('feedbackPeriod', {
                        rules: [{ required: true, message: '请选择选择反馈时长' }]
                    })(<Select placeholder="选择反馈时长">{renderOptions(feedbackPeriod)}</Select>)}
                </Form.Item>
            </Form>
        </Card>
    );
}

export default Form.create({})(LiepinForm);
